package com.ruoyi.wx.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.utils.WxConfig;
import com.ruoyi.wx.service.SkmWxPayService;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @Description: TODO
 * @Create by: jacob
 * @Date: 2025/7/20
 * 遇见未来的自己
 */
@Controller
@RequestMapping("/skmWxPay")
public class SkmWxPayController extends BaseController {
    @Autowired
    private SkmWxPayService skmWxPayService;

    @Anonymous
    @GetMapping("/test")
    public String test(){
        return "chenggong";
    }

    @Anonymous
    @GetMapping("/getJsapiTicket")
    @ResponseBody
    public AjaxResult getJsapiTicket(@RequestParam("url") String url) throws Exception {

        String ticket = skmWxPayService.getJsapiTicket();

        Long timestamp = System.currentTimeMillis();

        String nonceStr = IdUtils.randomUUID();

        String signature = WxConfig.sign(url, nonceStr, timestamp, ticket);

        JSONObject json = new JSONObject();
        json.put("appid", WxConfig.SP_APPID);
        json.put("timestamp", timestamp);
        json.put("nonceStr", nonceStr);
        json.put("signature", signature);
        return AjaxResult.success(json);
    }


    /** JSAPI支付下单，并返回JSAPI调起支付数据 */
    @PostMapping("prepayWithRequestPayment")
    @ResponseBody
    public AjaxResult prepayWithRequestPayment(@RequestParam("amount") String amountStr) {
        BigDecimal amount = new BigDecimal(amountStr);
        PrepayWithRequestPaymentResponse prepayWithRequestPaymentResponse = skmWxPayService.prepayWithRequestPayment(amount);
      return AjaxResult.success(prepayWithRequestPaymentResponse);
    }

    /**
     * 微信支付成功统一回调接口
     *
     * @param request
     * @return
     * @throws IOException
     */
    @Anonymous
    @PostMapping("wxPayCallback")
    public ResponseEntity.BodyBuilder wxPayCallback(HttpServletRequest request) throws IOException {
        return skmWxPayService.wxPayCallback(request);
    }
}
